package com.jule.goldfast.game.network.protocol.reqs;

import JoloProtobuf.GameSvr.JoloGame;
import com.jule.goldfast.base.enums.ErrorCodeEnum;
import com.jule.goldfast.game.gameUtil.GameLogic;
import com.jule.goldfast.game.model.PlayerInfo;
import com.jule.goldfast.base.enums.PlayerStateEnum;
import com.jule.goldfast.base.enums.TableStateEnum;
import com.jule.goldfast.game.network.protocol.ClientReq;
import com.jule.goldfast.game.network.protocol.acks.JoloGame_ReadyAck_50018;
import com.jule.goldfast.game.play.AbstractTable;
import com.jule.goldfast.game.service.TableService;
import com.jule.goldfast.game.vavle.notice.NoticeBroadcastMessages;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Slf4j
public class JoloGame_ReadyReq_50018 extends ClientReq {
    private long time;
    private JoloGame.JoloGame_ReadyReq req;

    public JoloGame_ReadyReq_50018(int functionId) {
        super(functionId);
    }

    @Override
    public void readPayLoadImpl(ByteBuf byteBuf) throws Exception {
        time = System.currentTimeMillis();
        byte[] blob = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(blob);
        req = JoloGame.JoloGame_ReadyReq.parseFrom(blob);
        AbstractTable table = TableService.getInstance().getTable(header.gameId + "", req.getRoomId(), req.getTableId());
        if (null != table) {
            this.setTable(table);
        } else {
            log.error("桌子不存在,roomId->" + req.getRoomId() + ", tableId->" + req.getTableId());
        }
    }

    @Override
    public void processImpl() throws Exception {
        log.debug("收到消息-> " + functionId + " reqNum-> " + header.reqNum + "msg ->" + req.toString());

        String userId = req.getUserId();
        //String gameOrderId = req.getGameOrderId();
        String roomId = req.getRoomId();
        int seatNum = req.getSeatNum();
        String tableId = req.getTableId();

        JoloGame.JoloGame_ReadyAck.Builder ack = JoloGame.JoloGame_ReadyAck.newBuilder();
        ack.setUserId(userId);
        ack.setRoomId(roomId);
        ack.setTableId(tableId);
        ack.setSeatNum(seatNum);
        ack.setResult(1);

        try {
            AbstractTable table = getTable();
            if (table == null) {
                log.info("table is null , userId = " + userId);
                return;
            }
            if (!table.getTableStateEnum().equals(TableStateEnum.GAME_READY)) {
                log.error("不在准备状态，客户端请把准备按钮隐藏");
                ack.setResult(-1).setResultMsg("不在准备状态，客户端请把准备按钮隐藏");
                ctx.writeAndFlush(new JoloGame_ReadyAck_50018(ack.build(), header));
                return;
            }
            //查找玩家信息
            PlayerInfo player = table.getPlayer(userId);
            //没在桌上
            if (!table.getInGamePlayersByPlayerId().containsKey(userId)) {
                ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50050_1.getCode());
                ctx.writeAndFlush(new JoloGame_ReadyAck_50018(ack.build(), header));
                return;
            }
            if (null == player) {
                ack.setResult(-1).setResultMsg(ErrorCodeEnum.GAME_50050_2.getCode());
                ctx.writeAndFlush(new JoloGame_ReadyAck_50018(ack.build(), header));
                return;
            }
            //设置自己的状态
            player.setState(PlayerStateEnum.game_ready);

            ack.addAllReadyList(readyInfos(table));

            ctx.writeAndFlush(new JoloGame_ReadyAck_50018(ack.build(), header));
            //广播我的状态
            NoticeBroadcastMessages.readyStatus(table, player);

            if (table.isAllActionOver(PlayerStateEnum.game_ready)) {
                GameLogic.betTimer(table);
            }

        } catch (Exception ex) {
            ack.setResult(10);
            ctx.writeAndFlush(new JoloGame_ReadyAck_50018(ack.build(), header));
            log.error(ex.getMessage(), ex);
        }
    }

    private List<JoloGame.JoloGame_ReadyInfo> readyInfos(AbstractTable table) {

        List<JoloGame.JoloGame_ReadyInfo> list = new ArrayList<>();
        Iterator<PlayerInfo> iter = table.getInGamePlayersBySeatNum().values().iterator();
        while (iter.hasNext()) {
            PlayerInfo playerInfo = iter.next();
            JoloGame.JoloGame_ReadyInfo.Builder info = JoloGame.JoloGame_ReadyInfo.newBuilder();
            info.setUserId(playerInfo.getPlayerId());
            info.setSeatNum(playerInfo.getSeatNum());
            info.setReadyStatus(playerInfo.getState().equals(PlayerStateEnum.game_ready) ? 1 : 0);
            list.add(info.build());
        }
        if (list.size() == 0) {
            log.error("readyInfos(): inGamePlayers.size():{}",table.getInGamePlayersBySeatNum().size());
        }
        return list;
    }
}
